package role

import (
	"context"
	"fmt"
	"net/http"
	"strings"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListLogic) List(req *types.RoleListRequest) (resp *types.RoleListResponse, err error) {
	resp = new(types.RoleListResponse)

	var query string
	var querys []string

	name := strings.TrimSpace(req.Name)
	if len(name) > 0 {
		querys = append(querys, fmt.Sprintf("name like '%%%s%%'", name))
	}

	if len(querys) > 0 {
		query = " where " + strings.Join(querys, " and ")
	}

	queryLimit := query + fmt.Sprintf(" order by sort_id asc limit %d,%d", (req.Page-1)*req.Size, req.Size)

	//1.统计总数
	total, err := l.svcCtx.RoleModel.Count(l.ctx, query)
	if err != nil {
		fmt.Printf("[Error]角色总数查询：%s\n", err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//2.查询分页
	roles, err := l.svcCtx.RoleModel.FindByPage(l.ctx, queryLimit)
	if err != nil {
		fmt.Printf("[Error]角色分页查询：%s\n", err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	resp.Data.Total = total
	for _, one := range roles {
		resp.Data.List = append(resp.Data.List, types.Role{
			Id:        one.Id,
			SortId:    one.SortId,
			Status:    one.Status,
			Name:      one.Name,
			Remark:    one.Remark,
			CreatedAt: one.CreatedAt.Unix(),
			UpdatedAt: one.UpdatedAt.Unix(),
		})
	}

	return resp, nil
}
